

package com.hazelcast.internal.server.tcp;

import com.hazelcast.internal.networking.HandlerStatus;
import com.hazelcast.internal.networking.InboundHandler;
import com.hazelcast.internal.networking.nio.InboundHandlerWithCounters;
import com.hazelcast.internal.nio.Packet;
import com.hazelcast.internal.nio.PacketIOHelper;
import com.hazelcast.internal.server.ServerConnection;

import java.nio.ByteBuffer;
import java.util.function.Consumer;

import static com.hazelcast.internal.networking.HandlerStatus.CLEAN;
import static com.hazelcast.internal.nio.IOUtil.compactOrClear;
import static com.hazelcast.internal.nio.Packet.FLAG_URGENT;

/**
 * The {@link InboundHandler} for member to member communication.
 * <p>
 * It reads as many packets from the src {@link ByteBuffer} as possible, and
 * each of the Packets is sent to the destination.
 *
 * @see Consumer
 * @see PacketEncoder
 */
public class PacketDecoder extends InboundHandlerWithCounters<ByteBuffer, Consumer<Packet>> {

    protected final ServerConnection connection;
    private final PacketIOHelper packetReader = new PacketIOHelper();

    public PacketDecoder(ServerConnection connection, Consumer<Packet> dst) {
        this.connection = connection;
        this.dst = dst;
    }

    @Override
    public void handlerAdded() {
        initSrcBuffer();
    }

    @Override
    public HandlerStatus onRead() throws Exception {
        src.flip();
        try {
            while (src.hasRemaining()) {
                Packet packet = packetReader.readFrom(src);
                if (packet == null) {
                    break;
                }
                onPacketComplete(packet);
            }

            return CLEAN;
        } finally {
            compactOrClear(src);
        }
    }

    protected void onPacketComplete(Packet packet) {
        if (packet.isFlagRaised(FLAG_URGENT)) {
            priorityPacketsRead.inc();
        } else {
            normalPacketsRead.inc();
        }

        packet.setConn(connection);

        dst.accept(packet);
    }
}
